import { type BunRequest } from "bun"
import assert from 'assert'
import { getRpcMethod } from "../rpc/core"
import { createErrorMessage, ErrorMessage } from "@packages/shared"
import jwt from "jsonwebtoken"
import env from "../utils/env"
import { traceLog } from "../utils/log"

export const headers = {
    "Access-Control-Allow-Origin": `*`,
    "Access-Control-Allow-Methods": "POST",
    "Access-Control-Allow-Headers": "Content-Type, Authorization"
}

const checkAuth = (tokenRaw: string) => {
    // 获取token
    const token = tokenRaw.split(' ').pop() ?? ''
    assert(token && token !== '', createErrorMessage(ErrorMessage.NotAuth))

    // 验证token
    assert(jwt.verify(token, env.JWT_SECRET), createErrorMessage(ErrorMessage.NotAuth))
}

const routes = {
    '/api/rpc/v1/:method': {
        // 预检请求处理
        OPTIONS: () => new Response(null, {
            headers,
        }),
        POST: async (req: BunRequest) => {

            //@ts-ignore
            const method = req.params.method

            // 获取rpc方法
            const rpc = getRpcMethod(method)
            assert(rpc, createErrorMessage(ErrorMessage.NotFound))

            // rpc是否需要鉴权校验
            rpc.auth && checkAuth(req.headers.get('Authorization') ?? '')

            // 校验参数
            const reqBody = await req.json()

            const param = rpc.validator.parse(reqBody)
            traceLog(`访问rpc方法：${method}`)
            const data = await rpc.handler(param)


            // 返回结果
            const res = new Response(JSON.stringify({
                code: 200,
                msg: 'ok',
                data,
            }), {
                status: 200,
                headers,
            })
            return res

        }
    }
}

export default routes